home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: new-news.sprintlink.net!eskimo!news
- From: mag@eskimo.com (mAg)
- Subject: Re: Can anyone help a newbie out ?
- X-Nntp-Posting-Host: tia1.eskimo.com
- Message-ID: <Dpw39z.1Gy@eskimo.com>
- Sender: news@eskimo.com (News User Id)
- Organization: *.*
- X-Newsreader: WinVN 0.93.10
- References: <4kkf3r$5b0@darwin.nbnet.nb.ca>
- Date: Mon, 15 Apr 1996 05:58:47 GMT
-
- In article <4kkf3r$5b0@darwin.nbnet.nb.ca> (Fri, 12 Apr 1996 02:38:04 GMT),
- lewwid@brunswickmicro.nb.ca says :
- >
- >I started reading a book on C, and i am stuck on one exercise, and i
- >know it's really simple, but i can't do it :(
- >
- >Problem:Write a function that accepts two strings. Count the number
- >of characters in each string, and return the pointer to the longer
- >string.
- >
- >This is what my lamer brain had to say ...
- >
- >#include <stdio.h>
- >
- >char *ptr, *ptr1;
-
- These are just pointers. They are pointing to nowhere. You can either say
-
- char ptr[512],ptr[512]; /* I've chosen 512 arbitrarily */
-
- or
-
- keep them as
- char *ptr, *ptr1;
-
- #include "string.h" at the start of the program and
-
- say
-
- if (!(ptr = malloc(512 * sizeof(char))) || !(ptr1 == malloc(512 * sizeof(char))))
- {
- printf("Out of memory\n");
- exit(1);
- }
- >
- >char checksize(char x[], char y[]);
-
- char *checksize(char x[], char y[]);
-
- >
- >main()
- >{
- > /* Prompt for input */
- >
- > puts("Please enter in the first string :");
- > gets(ptr);
- > puts("Now the second :");
- > gets(ptr1);
- >
- it is better to use fgets because you can specody the size and then the user cannot
- crash your program by typing a Loooooong string longer than your array size.
-
- > /* Print the longest pointer, and call checksize */
- >
- > printf("The char array that was longer is : %s", checksize(ptr,
- >ptr1));
- >
- > return 0;
- >}
- >/* Checksize .. checks to see which array of char is longer, and
- >returns the longest of the 2 */
- >char checksize(char x[], char y[])
-
-
- char *checksize(char x[], char y[])
- >{
- > int count, int total = 0, int total1 = 0;
- >
- > while (*x != NULL)
- > total += 1
- >
- > while (*y != NULL)
- > total1 += 1
- >
- > if (total < total2)
- > return *y;
-
- return(y);
-
- > if (total > total2)
- > return *x;
-
- return(x);
- >}
- >
- >
- > Yes i know, this is messy and very bad, but i am just starting out :)
- >
- > If someone could email me with any help, and good pointers, that would
- >be greatly appreciated ..
- >
- > lewwid@brunswickmicro.nb.ca
- >
-
- I guess everything else looks OK.
-
- --
- /* --------------------------------------------------------
- MAG@ESKIMO.COM
- http://www.eskimo.com/~mag/index.html
- ***********************************************************
- To understand recursion one must first understand recursion
- ***********************************************************
- -------------------------------------------------------- */
-
-